<script setup lang="ts">
import { ref, onMounted, watch, computed, nextTick } from 'vue'
import { ElTable, ElTableColumn, ElInput, ElSelect, ElOption } from 'element-plus'
import type { TableData } from '@/api/project/types'
import { getAccountApi } from '@/api/project'


interface AccountData {
  id?: number // 隐藏使用：提交时用 id，而不是 uid
  uid: string
  oprName: string
  score: number
  income?: number // 接口里可能没有小组字段，兼容可选
}

const props = defineProps({
  currentRow: {
    type: Object,
    default: () => null
  },
  // 需要在列表中默认勾选的 UID 集合
  preselectedUids: {
    type: Array as () => Array<string | number>,
    default: () => []
  }
})

const accountList = ref<AccountData[]>([])
const loading = ref(false)
const operatorCount = ref(0)

// 搜索与筛选
const search = ref('')
const smode = ref<number>(0)

// 选择计数
const selectedCount = ref(0)
// 已选择的数据
const selectedRows = ref<AccountData[]>([])

// 表格 ref
const tableRef = ref<InstanceType<typeof ElTable>>()

// 如果服务端分页/过滤，这里直接返回原数据
const filteredList = computed(() => accountList.value)

// 获取账户列表数据
const fetchAccountList = async () => {
  if (!props.currentRow?.id) return
  
  loading.value = true
  try {
    const response = await getAccountApi({
      id: props.currentRow.id,
      // 额外查询参数由后端识别
      search: search.value || undefined,
      smode: smode.value ?? undefined
    } as unknown as Partial<TableData>)
    if (response.data) {
      accountList.value = response.data.items
      operatorCount.value = accountList.value.length
      // 重置搜索与选择
      // 不清空本地搜索，以便回显
      selectedCount.value = 0
      selectedRows.value = []
      // 回显：根据传入的 preselectedUids 勾选已有行
      await nextTick()
      if (tableRef.value && props.preselectedUids && props.preselectedUids.length > 0) {
        const uidSet = new Set(props.preselectedUids.map(String))
        accountList.value.forEach((row) => {
          if (uidSet.has(String(row.uid))) {
            tableRef.value!.toggleRowSelection(row, true)
          }
        })
      }
    }
  } catch (error) {
    console.error('获取账户列表失败:', error)
    accountList.value = []
    operatorCount.value = 0
  } finally {
    loading.value = false
  }
}

// 监听 currentRow 变化，重新获取数据
watch(() => props.currentRow, (newRow) => {
  if (newRow?.id) {
    fetchAccountList()
  }
}, { deep: true })

// 组件挂载时获取数据
onMounted(() => {
  if (props.currentRow?.id) {
    fetchAccountList()
  }
})

// 表格选择变化
const onSelectionChange = (selection: AccountData[]) => {
  selectedCount.value = selection.length
  selectedRows.value = selection
}

// 搜索输入立即触发搜索
const onSearchInput = () => {
  fetchAccountList()
}

const onModeChange = () => {
  // 选择下拉立即触发
  fetchAccountList()
}

// 对外暴露方法：获取当前选择
defineExpose({
  getSelected: () => selectedRows.value
})
</script>

<template>
  <div class="member-list">   
    <div class="toolbar">
      <ElInput
        v-model="search"
        placeholder="搜索"
        clearable
        style="width: 60%; margin-right: 10px;"
        @input="onSearchInput"
      />
      <ElSelect v-model="smode" style="width: 38%;" placeholder="通过搜索" @change="onModeChange">
        <ElOption label="通过所有搜索" :value="0" />
        <ElOption label="通过UID搜索" :value="1" />
        <ElOption label="通过操手搜索" :value="2" />
        <ElOption label="通过小组搜索" :value="3" />
      </ElSelect>
    </div>

    <ElTable 
      v-loading="loading"
      :data="filteredList" 
      style="width: 100%"
      max-height="300"
      border
      ref="tableRef"
      @selection-change="onSelectionChange"
    >
    <ElTableColumn type="selection" width="55" align="center" />
    <!-- 隐藏列：不渲染但保留 id 在数据里用于提交 -->
    <ElTableColumn v-if="false" prop="id" label="ID" />
      <ElTableColumn 
        prop="uid" 
        label="UID" 
        
        align="center"
      />
      <ElTableColumn 
        prop="oprName" 
        label="操手" 
        align="center"
      />
      <ElTableColumn 
        prop="grpName" 
        label="小组" 
        align="center"
      />
      <ElTableColumn 
        prop="score" 
        label="当前总积分" 
        align="center"
      />
      
    </ElTable>
    <div class="selection-tip">已选择{{ selectedCount }}个账号</div>
  </div>
</template>

<style scoped>
.member-list {
  padding: 10px;
}

.toolbar {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 10px;
}

.selection-tip {
  margin-top: 8px;
  color: #606266;
  font-size: 12px;
}

.list-header {
  margin-bottom: 15px;
  border-bottom: 1px solid #ebeef5;
  padding-bottom: 10px;
}

.list-header h3 {
  margin: 0;
  color: #303133;
  font-size: 16px;
  font-weight: 500;
}
</style>